import { createConnection } from 'typeorm';

async function testDatabaseConnection() {
  console.log('正在测试MySQL连接...');

  try {
    const connection = await createConnection({
      type: 'mysql',
      host: 'localhost',
      port: 3306,
      username: 'root',
      password: '123456',
      database: 'test',
      synchronize: true,
      logging: true,
    });

    if (connection.isConnected) {
      console.log('✅ MySQL连接成功！');
      console.log(`连接详情:`);
      console.log(`- 数据库类型: ${connection.options.type}`);
      console.log(`- 主机: ${(connection.options as any).host}`);
      console.log(`- 端口: ${(connection.options as any).port}`);
      console.log(`- 数据库名: ${(connection.options as any).database}`);
      console.log(`- 用户名: ${(connection.options as any).username}`);

      // 尝试执行一个简单查询
      const result = await connection.query('SELECT 1 as test');
      console.log('✅ 查询测试成功:', result);

      await connection.close();
    } else {
      console.log('❌ MySQL连接失败：连接未建立');
    }
  } catch (error) {
    console.error('❌ MySQL连接失败：', error.message);
    console.error('详细错误：', error);

    // 提供一些可能的解决方案
    console.log('\n可能的解决方案：');
    console.log('1. 检查MySQL服务是否已启动');
    console.log('2. 确认数据库连接参数是否正确');
    console.log('3. 确认数据库用户是否有权限访问指定数据库');
    console.log('4. 检查防火墙设置是否阻止了连接');
  }
}

testDatabaseConnection();
